/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.ui.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.log4j.Logger;

import who.tmap.util.MiscHelper;

public class UserHomeHelper {

    private static Logger logger = Logger.getLogger(UserHomeHelper.class);	
	
	private static final String USER_HOME_PROPERTY ="user.home";
	
	private static final String TMAP_USER_HOME_DIR =".tmap";
	private static final String SAMPLES ="/samples.zip";
	private static final int BUFFER_SIZE =1024;
	
	private static String tmapDir =null;
	
	public String getTMapDir() throws IOException {
		if ( tmapDir == null ) {
			
			String currentPath =new File(".").getCanonicalPath();
		
			String userHome;
			
			// If run using web start or in a development environment context
			// use USER_HOME path
			if ( MiscHelper.isWebStart() || ArgumentsHelper.getInstance().contains( ArgumentsHelper.DEV_ENV ) ) {
				userHome =System.getProperty( USER_HOME_PROPERTY );
			// otherwise use current path (standalone context like usb key)
			} else {
				userHome =currentPath;
			}
			
			String tmapHomeStr =userHome + "/" + TMAP_USER_HOME_DIR;
			logger.debug( "tmap home=[" + tmapHomeStr + "]" );
			
			File tmapHome =new File( tmapHomeStr );
			if ( !tmapHome.exists() ) {
				tmapHome.mkdir();
				
				unzipSamples( SAMPLES, tmapHome );
			}
			
			tmapDir = tmapHomeStr + "/";
		}
		
		return tmapDir;
	}
	
	public void unzipSamples() throws IOException {
		unzipSamples( SAMPLES, new File( tmapDir ) );
	}

	private void unzipSamples( String resourceName, File tgtDir ) throws IOException {
	    BufferedOutputStream dest = null;
	    
	    ZipInputStream zis = new ZipInputStream(new BufferedInputStream( getClass().getResourceAsStream( resourceName ) ) );	    
	    ZipEntry entry;
	    while((entry = zis.getNextEntry()) != null) {
	    	logger.debug("extracting " + entry );
	        int count;
	        byte data[] = new byte[BUFFER_SIZE];
	        
	        File entryFile =new File( entry.getName() );
	        if ( entryFile.getParentFile() != null ) {
	        	new File( tgtDir + "/" + entryFile.getParent() ).mkdir();
	        } 
	        
	        if ( !entryFile.isDirectory() && entry.getSize() > 0 ) {
	        
		        FileOutputStream fos = new FileOutputStream( tgtDir + "/" + entry.getName() );
		        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
		        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
		        	dest.write(data, 0, count);
		        }
		        dest.flush();
		        dest.close();
	        }
	    }
	    
	    zis.close();
	}
	
}
